<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>新闻内容</h3>
      <el-form ref="dataForm" :rules="rules" :model="news" label-width="150px">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="news.title" placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="新闻简介" prop="intro">
          <el-input v-model="news.intro" placeholder="请输入新闻简介" />
        </el-form-item>
        <!--<el-form-item label="新闻分类" prop="category">
          <el-select v-model="news.category" placeholder="选择新闻分类">
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        -->
        <el-form-item label="新闻图片" prop="banner">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :on-success="handleimgsUrl"
            :on-error="handleErrorimgsUrl"
            :before-upload="beforeAvatarUpload"
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture"
            class="upload-img"
          >
            <div v-loading="loading" class="preimg" />
            <div v-show="news.banner" :style="'background-image:url('+news.banner+')'" class="preimg" />
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件，且不超过2M</div>
          </el-upload>
          <el-input v-model="news.banner" type="hidden" class="hidden-input" />
        </el-form-item>
        <el-form-item label="上传附件" prop="fileUrl">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :limit="100"
            :file-list="fileList"
            :on-exceed="uploadOverrun"
            :on-success="handlefilesUrl"
            :on-remove="handleRemove"
            multiple
            accept=".doc, .docx, .pdf, .xls, .xlsx, ppt, pptx, pdf"
          >
            <div slot="tip" class="el-upload__tip">只能上传.doc/.docx/.pdf/.xls/.xlsx/ppt/pptx/ pdf文件</div>
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="新闻内容" prop="text">
          <editor :init="editorInit" v-model="news.text" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-if="!news.id" type="primary" @click="handleCreate">保存新闻</el-button>
      <el-button v-if="news.id" type="primary" @click="handleEdit">更新新闻</el-button>
    </div>
  </div>
</template>

<style>
  .hidden-input{
    display: block;
    width:0px;
    height:0px;
  }
  .el-upload--picture{
    position: relative;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    cursor: pointer;
    line-height: 146px;
    vertical-align: top;
  }
  .el-upload-list--picture{
    display: none;
  }
  .upload-img .preimg{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background-repeat:no-repeat;
    background-size:contain;
    background-position:center;
  }
  .el-loading-spinner{
    top:0;
  }
</style>

<script>
import { editNews, createNews, detailNews } from '@/api/news'
import { categoryTabList } from '@/api/categorylist'
import { uploadPath, createStorage } from '@/api/storage'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'NewsAdd',
  components: { Editor },
  data() {
    return {
      newsId: '',
      uploadPath,
      news: {
        banner: '', fileUrl: '', fileName: '', category: '1'
      },
      typeList: [],
      fileList: [],
      fileUrl: [],
      fileName: [],
      rules: {
        title: [
          { required: true, message: '新闻标题不能为空', trigger: 'blur' }
        ],
        banner: [
          { required: true, message: '新闻图片不能为空', trigger: 'blur' }
        ],
        intro: [
          { required: true, message: '新闻简介不能为空', trigger: 'blur' }
        ],
        text: [
          { required: true, message: '新闻内容不能为空', trigger: 'blur' }
        ]
      },
      loading: false,
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        width: 600,
        height: 400,
        content_style: 'img {width:100%;height:auto;} p {margin:16px 0 0;font-size: 15px;color: #666666;text-align: justify;line-height: 22px;}',
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }

    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function() {
      const newsId = this.$route.query.id
      if (newsId) {
        detailNews(newsId).then(response => {
          this.news = Object.assign({}, response.data.data)
          if (this.news.fileUrl) {
            this.fileUrl = this.news.fileUrl.split(',')
            this.fileName = this.news.fileName.split(',')
            const arr = []
            this.fileUrl.forEach((item, index) => {
              arr.push({
                name: this.fileName[index],
                url: item
              })
            })
            this.fileList = arr
          }
        })
      }
      categoryTabList()
        .then(response => {
          this.typeList = response.data.data
        })
        .catch(() => {})
    },
    handleCancel: function() {
      this.$router.push({ path: '/enterprise/news' })
    },
    handleCreate: function() {
      this.formValidate(1)
    },
    handleEdit: function() {
      this.formValidate(2)
    },
    formValidate: function(type) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalNews = {
            ...this.news
          }
          finalNews.fileUrl = this.fileUrl.join(',')
          finalNews.fileName = this.fileName.join(',')
          if (type === 1) {
            createNews(finalNews)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.$router.push({ path: '/enterprise/news' })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          } else if (type === 2) {
            editNews(finalNews)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.$router.push({ path: '/enterprise/news' })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善以上表单'
          })
        }
      })
    },
    handleimgsUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.news.banner = response.url
        this.loading = false
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 / 2 < 2
      this.loading = true
      if (!isLt2M) {
        this.$notify.error({
          title: '失败',
          message: '请重新上传2MB以内的图片'
        })
        this.loading = false
      }
      return isLt2M
    },
    handleErrorimgsUrl(response, file, fileList) {
      this.$notify.error({
        title: '失败',
        message: '请重新上传图片'
      })
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.fileUrl.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.url
        }

        if (this.fileUrl[i] === url) {
          this.fileUrl.splice(i, 1)
          this.fileName.splice(i, 1)
        }
      }
    },
    handlefilesUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.fileUrl.push(response.url)
        this.fileName.push(file.name)
      }
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传100个附件!'
      })
    }

  }
}
</script>
